package com.bhs.service.Menu.impl;

import com.bhs.mappers.menu.LeftMenuMapper;
import com.bhs.pojo.Item;
import com.bhs.pojo.MainMenu;
import com.bhs.pojo.Menu;
import com.bhs.service.Menu.LeftMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LeftMenuServiceImpl implements LeftMenuService {
    @Autowired
    private LeftMenuMapper leftMenuMapper;

    @Override
    public List<Menu> getLeftMenu() {
        return leftMenuMapper.getLeftMenu();
    }

    @Override
    public List<Item> getLeftItemList(Integer id) {
        return leftMenuMapper.getLeftItemList(id);
    }

    @Override
    public List<MainMenu> getAllItemList() {
        List<MainMenu> mainMenu = leftMenuMapper.getMainMenu();
        List<MainMenu> mainMenuList = new ArrayList<>();
        Map<Integer, List<Item>> map = getItemMap();
        System.out.println();
        for (MainMenu item : mainMenu){
            Integer menuId = item.getId();
            List<Item> item1 = map.get(menuId);
            // 如果为空说明改分类无对应的商品，不执行后两行代码就不会返回前端
            if (item1==null){
                continue;
            }
            item.setChildren(item1);
            mainMenuList.add(item);
        }
        return mainMenuList;
    }
    // 将商品封装到一个map中
    public Map<Integer,List<Item>> getItemMap(){
        HashMap<Integer, List<Item>> map = new HashMap<>();
        List<Item> itemList = leftMenuMapper.getMainItem();
        for (Item item : itemList){
            Integer key = item.getMainMenuId();
            if (map.containsKey(key)){
                List<Item> list = map.get(key);
                // 如果列表个数大于10则不添加
                if (list.size()>=10){
                    continue;
                }
                list.add(item);
                continue;
            }
            List<Item> list = new ArrayList<>();
            list.add(item);
            map.put(key, list);
        }
        return map;
    }
}
